#include "pontuacao.h"

void desenhaPontuacao(){
	int i=0, x=26, y=10;
	Pontuacao* best[10];//Cria o array com os melhores jogadores
	for(i=0; i<10; i++){
		best[i] = malloc(sizeof(Pontuacao));
		best[i]->nome = malloc(sizeof(char*));
	}
	//Carrega as pontuacoes actuais
	getPontuacao(best);
	//Passa para string
	gotoxy(x, y);
	printf("Jogador        |   Pontuacao");
	y+=2;
	for(i=0; i<10; i++){
		gotoxy(x, y);
		printf("%s", best[i]->nome);
		gotoxy(x+15, y);
		printf("%s%d", "| ", best[i]->pontos);
		y++;
	}
	
	gotoxy(23, ++y);
	printf("Pressione espaco para continuar\n");
	while(key != SPACE){};
	
}

void getPontuacao(Pontuacao** best){
	static const char filename[] = "pontuacao.txt";
	FILE *file = fopen ( filename, "r" ); //open file in read mode
	int i=0;
	
	if ( file != NULL ){
		char line [ 128 ];
		i=0;
		int tmp_p=0;
		while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
		{
			char *tmp= "";
			tmp = strtok(line, "|"); //getname
			strcpy(best[i]->nome, tmp);		//setname
			tmp = strtok(NULL, "|");//getpoints
			tmp_p = atoi(tmp);
			best[i]->pontos = tmp_p;//setpointss
			i++;
		}
		fclose ( file );
	}
	else	
		perror ( filename );

}


void setPontuacao(Pontuacao** best){
	static const char filename[] = "pontuacao.txt";
	FILE *file = fopen ( filename, "w" ); //open file in read mode
	int i=0;

	char line [ 128 ];
	i=0;
	for(i=0; i<10; i++)
	{	sprintf(line, "%s|%d\n", best[i]->nome, best[i]->pontos);
		fprintf(file, line);
	}
	fclose ( file );

}

int updatePontuacao(Pontuacao** best, Pontuacao* jogador){
	int i=0, n=0, last=0;
	Pontuacao* temp[10];
	for(i=0; i<10; i++){
		temp[i] = malloc(sizeof(Pontuacao));
		temp[i]->nome = malloc(sizeof(char*)*14);
		strcpy(temp[i]->nome, best[i]->nome);
		temp[i]->pontos = best[i]->pontos;
	}
	i=0;
	while(n<10){
		if(jogador->pontos > temp[i]->pontos && last != 1){
			strcpy(best[n]->nome, jogador->nome);
			best[n]->pontos = jogador->pontos;
			last=1;
		}
		else{
			strcpy(best[n]->nome, temp[i]->nome);
			best[n]->pontos = temp[i]->pontos;
			i++;
		}
		n++;
	}
	return last;
}
